package com.dbh.alg.algorithm.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.IntStream;

/**
 * 手写一个java线程池
 */
@Slf4j
public class YesThreadPool {

    // 存放任务的阻塞对列
    BlockingQueue<Runnable> taskQueue;

    // 线程列表
    List<YesThread> threads;

    YesThreadPool(BlockingQueue<Runnable> taskQueue, int threadSize) {
        this.taskQueue = taskQueue;
        threads = new ArrayList<>();
        // 初始化线程并定义名称
        IntStream.rangeClosed(1, threadSize).forEach((i) -> {
            YesThread thread = new YesThread("yes-task-thread-" + i);
            thread.start();
            threads.add(thread);
        });
    }

    public void execute(Runnable task) throws InterruptedException {
        taskQueue.put(task);
    }

    // 自定义线程
    class YesThread extends Thread {
        public YesThread (String name) {
            super(name);
        }

        @Override
        public void run() {
            while (true) {
                Runnable task = null;
                try {
                    task = taskQueue.take();
                } catch (InterruptedException e) {
                    log.error("记录一点东西...", e);
                }
                task.run();
            }
        }
    }

    public static void main(String[] args) {
        YesThreadPool pool = new YesThreadPool(new LinkedBlockingDeque<>(10), 3);
        IntStream.rangeClosed(1, 5).forEach((i) -> {
            try {
                pool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "1111");
                });
            } catch (InterruptedException e) {
                log.error("记录点东西...", e);
            }
        });
    }
}
